package com.contexttree.filereader;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * This class read the txt file with one or more query to be analized and compose two queries
 * Politecnico di Milano 2012
 * @author Paolo Barbaglia
 * @author Filippo Ferrari
 *
 */
public class QueryBuilder {
	
	/**
	 * Read txt file with query to be analyzed
	 * @param filename
	 * @return queryString
	 */
	public static String readQueryFile(String filename){
		String queryString = "";
        
		try{
			FileInputStream fstream = new FileInputStream(filename);
	        DataInputStream in = new DataInputStream(fstream);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
	        String strLine;
	        
	        while ((strLine = br.readLine()) != null){
	        	queryString += (strLine+" ");
	        }
	        in.close();
	        
	    }catch (Exception e){
	        System.err.println("Errore: " + e.getMessage());
	    }
		//Substitute multiple space with only one
		queryString = queryString.replaceAll("( )+", " ");
		return queryString;		
	}
	
	/**
	 * Build query with different type passed
	 * @param tableName
	 * @param keyField
	 * @param queryString
	 * @param selectQuery
	 * @param type
	 * @return executableQuery String query
	 */
	public static String buildQuery(String tableName, String keyField, String queryString, String selectQuery, String type){
		String executableQuery = "";
		
		//Substitute multiple space with only one
		queryString = queryString.replaceAll(";", "");
		queryString = queryString.replaceAll("( )+", " ");
		executableQuery = selectQuery + " AND " + tableName + "." + keyField + " " + type + " (" + queryString +")";
		return executableQuery;
	}
}